package com.qiu.DitingPlatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiu.DitingPlatform.common.ErrorCode;
import com.qiu.DitingPlatform.common.ResultUtils;
import com.qiu.DitingPlatform.exception.BusinessException;
import com.qiu.DitingPlatform.exception.ExceptionUtils;
import com.qiu.DitingPlatform.model.domain.User;
import com.qiu.DitingPlatform.service.UserService;
import com.qiu.DitingPlatform.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.qiu.DitingPlatform.contant.UserConstant.USER_Login_STATE;

/**
 * 用户服务实现类
 *
 * @author QIU
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-02-27 23:05:02
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    // 加密盐
    private static final String salt = "qiu";

    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    /**
     * 用户注册
     *
     * @param userAccount   用户账号
     * @param userPassword  用户密码
     * @param checkPassword 确认密码
     * @param plantcode     编号
     * @return 成功返回用户id，失败返回-1
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String plantcode) {
        // 校验参数
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, plantcode)) {
            ExceptionUtils.error(ErrorCode.PARAM_NOT_NULL, "参数不能为空");
        }

        // 校验账号长度
        if (userAccount.length() < 4) {
            ExceptionUtils.error(ErrorCode.PARAM_ERROR, "账号长度不能小于4");
        }
        // 校验编号长度
        if (plantcode.length() > 5) {
            ExceptionUtils.error(ErrorCode.PARAM_ERROR, "编号长度不能大于5");
        }

        // 校验密码是否一致
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            ExceptionUtils.error(ErrorCode.PARAM_ERROR, "密码或者校验密码长度不能小于8");
        }

        // 校验账户不能包含特殊字符
        String regex = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；’，。、《》？「『」』]";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if (matcher.find()) {
            ExceptionUtils.error(ErrorCode.PARAM_ERROR, "账号不能包含特殊字符");
        }

        // 密码和确认密码一致
        if (!userPassword.equals(checkPassword)) {
            ExceptionUtils.error(ErrorCode.PARAM_ERROR, "密码和校验密码不相同");
        }

        // 用户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.count(queryWrapper);
        if (count > 0) {
            ExceptionUtils.error(ErrorCode.PARAM_NOT_NULL, "参数不能为空");
        }

        // 编号不能重复
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("plantcode", plantcode);
        long count1 = this.count(queryWrapper1);
        if (count1 > 0) {
            ExceptionUtils.error(ErrorCode.SQL_ERROR, "编号不能重复");
        }

        // 2. 加密密码
        String encryptedPassword = DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());

        // 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptedPassword);
        user.setPlantcode(plantcode);
        boolean saveResult = this.save(user);
        // 保存失败
        if (!saveResult) {
            ExceptionUtils.error(ErrorCode.SQL_ERROR, "插入数据失败,注册失败");
        }

        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账号
     * @param userPassword 用户密码
     * @param request      请求
     * @return 成功返回用户信息，失败返回null
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 校验参数
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            ExceptionUtils.error(ErrorCode.PARAM_NOT_NULL, "参数不能为空");
        }

        // 校验账号长度
        if (userAccount.length() < 4) {
            ExceptionUtils.error(ErrorCode.PARAM_ERROR, "账号长度不能小于4");

        }

        // 校验密码是否一致
        if (userPassword.length() < 8) {
            ExceptionUtils.error(ErrorCode.PARAM_ERROR, "密码长度不能小于8");

        }

        // 校验账户不能包含特殊字符
        String regex = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；’，。、《》？「『」』]";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if (matcher.find()) {
            ExceptionUtils.error(ErrorCode.PARAM_ERROR, "账号不能包含特殊字符");

        }


        // 2. 加密密码
        String encryptedPassword = DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());
        // 查询密码和加密密码是否一致
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptedPassword);
        User user = userMapper.selectOne(queryWrapper);

        // 用户不存在或密码错误
        if (user == null) {
            log.info("user login failed,userAccount cannot match password ,userAccount:{}", userAccount);
            ExceptionUtils.error(ErrorCode.SQL_ERROR, "账号或密码错误");
        }

        // 用户脱敏
        User safetyUser = geySafetyUser(user);

        // 记录记录用户的登录状态
        request.getSession().setAttribute(USER_Login_STATE, safetyUser);

        // 返回用户信息
        return safetyUser;
    }

    /**
     * 获取用户信息，脱敏
     *
     * @param originUser 原始用户信息
     * @return 脱敏后的用户信息
     */
    @Override
    public User geySafetyUser(User originUser) {
        if (originUser == null) {
            ExceptionUtils.error(ErrorCode.PARAM_NOT_NULL, "脱敏前的有效用户信息不能为空");
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvtarUrl(originUser.getAvtarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUpdateTime(originUser.getUpdateTime());
        safetyUser.setPlantcode(originUser.getPlantcode());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request 请求体
     */

    @Override
    public String  userLogout(HttpServletRequest request) {
        //移除用户登录状态
        request.getSession().removeAttribute(USER_Login_STATE);
        return "退出成功";
    }
}




